const mongoose = require("mongoose");
const baseModel = require("./base-modal");
const md5 = require("../util/md5");

function formatDateToYMDHMS(date) {
  if (!date) return date;
  const d = new Date(date);
  const pad = (n) => String(n).padStart(2, "0");
  const yyyy = d.getFullYear();
  const MM = pad(d.getMonth() + 1);
  const dd = pad(d.getDate());
  const HH = pad(d.getHours());
  const mm = pad(d.getMinutes());
  const ss = pad(d.getSeconds());
  return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`;
}

const articleSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  body: {
    type: String,
    required: true,
  },
  tagList: {
    type: [String],
    default: null,
  },
  favoritesCount: {
    type: Number,
    default: 0,
  },
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  },
  ...baseModel, // 继承baseModel
});

// 输出时统一格式化时间字段
articleSchema.set("toJSON", {
  transform: function (doc, ret) {
    if (ret.createdAt) ret.createdAt = formatDateToYMDHMS(ret.createdAt);
    if (ret.updatedAt) ret.updatedAt = formatDateToYMDHMS(ret.updatedAt);
    return ret;
  },
});

articleSchema.set("toObject", {
  transform: function (doc, ret) {
    if (ret.createdAt) ret.createdAt = formatDateToYMDHMS(ret.createdAt);
    if (ret.updatedAt) ret.updatedAt = formatDateToYMDHMS(ret.updatedAt);
    return ret;
  },
});

// 保存与更新时自动维护 updatedAt
articleSchema.pre("save", function (next) {
  this.updatedAt = new Date();
  next();
});

articleSchema.pre("findOneAndUpdate", function (next) {
  this.set({ updatedAt: new Date() });
  next();
});

module.exports = mongoose.model("Article", articleSchema);
